package com.lkm.app_ui.ui;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.FunHelp;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.MyApplication;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.help.PrinterHelp;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.event.OnSubtotalRealEvent;
import com.lkm.app_ui.log.AppLogger;
import com.lkm.app_ui.m.fun.FunModule;
import com.lkm.app_ui.m.fun.OnKeyNumberEvent;
import com.lkm.app_ui.m.fun.OnPayEvent;
import com.lkm.app_ui.m.fun.OnSaleManifestSyncEvent;
import com.lkm.app_ui.m.fun.SaleManifestEntity;
import com.lkm.app_ui.m.order_img.OnGoodImageTackEvent;
import com.lkm.comlib.help.ImageViewLoadHelp;
import com.lkm.comlib.help.ViewHelp;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.comlib.ui.BaseHoldAdapter;
import com.lkm.comlib.ui.IHoldView;
import com.lkm.frame.P;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.Observer;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.JsonP;
import com.lkm.javatool.NumberHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.javatool.lang.RunnablePR;
import com.lkm.market2_0.ExpandConfig;
import com.lkm.market2_0.entity.SteelyardInfo;
import com.lkm.market2_0.help.SteelardHelp;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyarddata.SteelyardDataModule;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.market2_0.m.steelyardserver.SteelyardServerModule;
import com.lkm.market2_0.m.steelyardserver.to.WeightChangeInfo;
import com.lkm.market2_0.m.steelyarddata.OnSteelardInfoLoadEvent;
import com.lkm.market2_0.m.steelyardserver.event.OnSubtotalEvent;
import com.lkm.market2_0.m.steelyardserver.event.OnWeightInfoChangeEvent;
import com.lkm.market2_0.task.DefaultTaskExecutor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

@Deprecated // 被com.lkm.app_ui.ui.sale 替代了
public class SaleFragment extends MBaseFragment {

    public static SaleFragment saleFragment = null;

    public static SaleFragment getInstance() {
        SaleFragment f = new SaleFragment();
        Bundle data = new Bundle();
        f.setArguments(data);
        return f;
    }

    private MAdapter adapter;

    private Handler mainHandler;

    private static int requestCode_FUN = 1;

    @Override
    protected int configLayoutResID() {
        return R.layout.fragment_sale;
    }

    @Override
    protected boolean configIsLockKey() {
        return false;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        saleFragment = this;
    }


    private ImageView img_good;
    private ImageViewLoadHelp payImageViewLoadHelp;
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mainHandler = new Handler(Looper.getMainLooper());

        listView = (ListView) findViewById(android.R.id.list);
        listView.setAdapter(adapter = new MAdapter());
        img_good = findViewById(R.id.img_good);
        ((TextView)findViewById(R.id.tv_weight_unit_title)).setText("重量("+RunTimeData.getAppWeightUnit()+")");

        ((TextView)findViewById(R.id.tv_weight_unit)).setText("("+RunTimeData.getAppWeightUnit()+")");
        ((TextView)findViewById(R.id.tv_price_weight_unit)).setText("(元/"+RunTimeData.getAppWeightUnit()+")");

        payImageViewLoadHelp = new ImageViewLoadHelp(getActivity(), Math.max(getResources().getDisplayMetrics().heightPixels, getResources().getDisplayMetrics().widthPixels), holdCycleHelp());
        payImageViewLoadHelp.setHasImagScaleType(ImageView.ScaleType.CENTER_INSIDE);
        payImageViewLoadHelp.setLoadingImagScaleType(ImageView.ScaleType.CENTER_INSIDE);
        payImageViewLoadHelp.setNotImagScaleType(ImageView.ScaleType.CENTER_INSIDE);
//        payImageViewLoadHelp.setImage(img_good, new File("/sdcard/ast-market/orderImgUpSZs/").listFiles()[1].getAbsolutePath());

        reOnGoodImageTackEvent();
        reOnSteelardInfoLoadEvent();
        reOnWeightInfoChangeEvent();
        reOnOrderAddEvent();
        reOnSubtotalEvent();
        reOnKeyEvent();
        reOnKeyNumberEvent();


        tv_name1 = ((TextView) findViewById(R.id.tv_name1));//.setText(weightChangeInfo.getName());
        tv_weight1 = ((TextView) findViewById(R.id.tv_weight1));//.setText(NumberHelp.formatMoney(weightChangeInfo.getWeight(), 3, "--"));
        tv_price1 = ((TextView) findViewById(R.id.tv_price1));//.setText(SteelardHelp.formatMoney(weightChangeInfo.getUnitPrice()));
        tv_money = ((TextView) findViewById(R.id.tv_money));
    }

    private TextView tv_name1,tv_weight1,tv_price1,tv_money;

    private ListView listView;



    private void reOnGoodImageTackEvent(){
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnGoodImageTackEvent>(){
            @Override
            public void onReceiver(OnGoodImageTackEvent data) {



                if(!isExit())
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            boolean isP = false;

                            if(souceList!=null) {
                                List<OrderEntity.GoodEntity> gs = new ArrayList<>(souceList);
                                for (OrderEntity.GoodEntity ge : gs) {
                                    if (data.goodEntity.itemId == ge.itemId) {
                                        isP = true;
                                        break;
                                    }
                                }
                            }
                            if(!isExit()&&isP) {

                                payImageViewLoadHelp.setImage(img_good, data.imgPath);

                                AlphaAnimation animation = new AlphaAnimation(1, 0);
                                animation.setFillAfter(true);
                                animation.setDuration(500);
                                animation.setStartOffset(1000);

                                ((View) img_good.getParent()).startAnimation(animation);

                                if(onGoodImageTackrun!=null)
                                onGoodImageTackrun.run();
                            }
                        }
                    });

            }

            @Override
            public Class<OnGoodImageTackEvent> getBusEventClass() {
                return OnGoodImageTackEvent.class;
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    private void reOnSteelardInfoLoadEvent() {
        try {
            ((TextView) findViewById(R.id.tv_title)).setText(RunTimeData.organizationInfo.getName()+" "+ RunTimeData.steelyardInfo.getStallEntity().getStallName());
        } catch (Exception e) {
        }
        LinkBusCycleWrapper.register(new Observer<OnSteelardInfoLoadEvent>() {
            @Override
            public Class<OnSteelardInfoLoadEvent> getBusEventClass() {
                return OnSteelardInfoLoadEvent.class;
            }

            @Override
            public void onReceiver(OnSteelardInfoLoadEvent data, Runnable nextRun) {

                try {
                    try {
                        ((TextView) findViewById(R.id.tv_title)).setText(RunTimeData.organizationInfo.getName()+" "+RunTimeData.steelyardInfo.getStallEntity().getStallName());
                    } catch (Exception e) {
                    }
                } finally {
                    nextRun.run();
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    private void reOnSubtotalEvent() {
        LinkBusCycleWrapper.register(new Observer<OnSubtotalEvent>() {
            @Override
            public Class<OnSubtotalEvent> getBusEventClass() {
                return OnSubtotalEvent.class;
            }

            @Override
            public void onReceiver(OnSubtotalEvent data, Runnable nextRun) {
                try {
                    AppLogger.Order.onSubtotalToUI();


                    String steelyardMac = data.getSteelyardMac();

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            int oldSize = CollectionHelp.getSize(souceList);

                            souceList.clear();

                            if (mSteelyardDataModule == null)
                                mSteelyardDataModule = ExpandConfig.instance.getModuleManager().loadModule(SteelyardDataModule.class);
                            List<OrderEntity.GoodEntity> goodEntities = null;

                            if (mSteelyardDataModule != null) {
                                goodEntities = mSteelyardDataModule.getGoodEntities(steelyardMac);


                                if (goodEntities != null) {
                                    for (int i = 0; i < goodEntities.size(); i++) {
//                                        if (goodEntities.get(i).weight <= 0 || goodEntities.get(i).unitType == 2) {

                                        if (goodEntities.get(i).weight <= 0 ) {
                                            mSteelyardDataModule.removeGoodEntities(steelyardMac, i);
                                            goodEntities = mSteelyardDataModule.getGoodEntities(steelyardMac);
                                            i = 0;
                                        }
                                    }
                                }


                                int newSize = CollectionHelp.getSize(goodEntities);


                                if(newSize > oldSize){
                                    OrderEntity.GoodEntity[] readGoodEntities = goodEntities==null? new OrderEntity.GoodEntity[0]: goodEntities.toArray(new OrderEntity.GoodEntity[goodEntities.size()]);
                                    LinkBus.sendBroadcast(new OnSubtotalRealEvent(readGoodEntities,new OrderEntity.GoodEntity[]{data.getGoodEntitie()},true));
                                }

                            }

                            try {
                                souceList.addAll(goodEntities);
                            } catch (Exception e) {
                            }
                            adapter.notifyDataSetChanged();

                            if(isSubtotalGopay){
                                isSubtotalGopay = false;

                                mainHandler.postDelayed(onGoodImageTackrun = new Runnable() {
                                    @Override
                                    public void run() {

                                        if(onGoodImageTackrun != null) {
                                            onGoodImageTackrun = null;

                                            goPayUI();
                                        }


                                    }
                                }, AppConfig.isOrderImgTack() ? 3500:0);

                            }

                        }
                    });

                } finally {
                    nextRun.run();
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }
    Runnable onGoodImageTackrun = null;



    private void reOnOrderAddEvent() {
        LinkBusCycleWrapper.register(new Observer<OnPayEvent>() {
            @Override
            public Class<OnPayEvent> getBusEventClass() {
                return OnPayEvent.class;
            }

            @Override
            public void onReceiver(OnPayEvent data, Runnable nextRun) {
                try {
                    if (!data.isSuccess()) {
                        return;
                    }


                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (data.getOrderEntity().type == OrderEntity.TYPE_Full1) {


                                onPayOk( data.getOrderEntity());

                                clearAll();



                            }

//                            ViewUIHelp.showTipsLong(MainActivity.this, "OnOrderAddEvent");

//                            souceList.addAll(data.getOrderEntity().goods);


                        }
                    });


                } finally {
                    nextRun.run();
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    private void reOnWeightInfoChangeEvent() {
        LinkBusCycleWrapper.register(new Observer<OnWeightInfoChangeEvent>() {
            @Override
            public Class<OnWeightInfoChangeEvent> getBusEventClass() {
                return OnWeightInfoChangeEvent.class;
            }

            @Override
            public void onReceiver(OnWeightInfoChangeEvent data, Runnable nextRun) {
                try {
                    String steelyardMac = data.getSteelyardMac();

                    WeightChangeInfo weightChangeInfo = data.getWeightChangeInfo();

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isExit()) return;

                            tv_name1.setText(weightChangeInfo.getName());
                            tv_weight1.setText(NumberHelp.formatMoney(weightChangeInfo.getWeight(), 3, "--"));
                            tv_price1.setText(SteelardHelp.formatMoney(weightChangeInfo.getUnitPrice()));

                            cur_weightTotalPrice = weightChangeInfo.getTotalPrice();
                            tv_money.setText(SteelardHelp.formatMoney(weightChangeInfo.getTotalPrice()));
                            upTprice1();
//                            ((TextView) findViewById(R.id.tv_tprice1)).setText(formatMoney(weightChangeInfo.getTotalPrice(), 2, "--"));
                        }
                    });


                } finally {
                    nextRun.run();
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    private void reOnKeyEvent() {
        LinkBusCycleWrapper.register(new Observer<OnSteelyardKeyEvent>() {
            @Override
            public Class<OnSteelyardKeyEvent> getBusEventClass() {
                return OnSteelyardKeyEvent.class;
            }

            @Override
            public void onReceiver(OnSteelyardKeyEvent data, Runnable nextRun) {
                try {
                    if (data.isIntercepted()) return;

                    if(clearAllDialog!=null){
                        if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_9) {
                            clearAll();
                        }

                        try {
                            FunModule steelyardServerModule = AppConst.getModuleManager().loadModule(FunModule.class);
                            steelyardServerModule.setLockKeySwitch(!true);
                        } catch (Exception e) {
                        }
                        clearAllDialog.dismiss();

                    }else

                    if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_PAY) {
                        data.setIntercepted(true);

                        RunTimeData.isQuickPay = true;
                        goPayUI();
                    } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN) {
                        data.setIntercepted(true);

//                        AppConst.getModuleManager().loadModule(NFC_Module.class).watchCardBlockTask();

                        if(isEditSubtotal){

                            editSubtotal(false);
                        }else {

                            RouterUINavigation.getInstance().showSaleFun((BaseFragmentActivity) getActivity(), SaleFragment.this, requestCode_FUN);
                        }
                    } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_CLEAR) {
                        data.setIntercepted(true);

                        if (clearAllDialog == null) {
                            clearAllDialog = ViewUIHelp.showAlertTipsDialog(getActivity(), "是否清除累计？如果是结账，请按“支付打印”完成订单", "确认清除（按9）", null);
                            clearAllDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    clearAllDialog = null;
                                }
                            });
                            ((TextView)clearAllDialog.findViewById(R.id.tv_tips)).setTextSize(40);
                            ((TextView)clearAllDialog.findViewById(R.id.tv_ok)).setTextSize(40);
                            try {
                                FunModule steelyardServerModule = AppConst.getModuleManager().loadModule(FunModule.class);
                                steelyardServerModule.setLockKeySwitch(true);
                            } catch (Exception e) {
                            }
                        }
                    }
                } finally {
                    nextRun.run();
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }
    private Dialog clearAllDialog;


    private void reOnKeyNumberEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnKeyNumberEvent>() {
            @Override
            public Class<OnKeyNumberEvent> getBusEventClass() {
                return OnKeyNumberEvent.class;
            }

            @Override
            public void onReceiver(OnKeyNumberEvent data) {
                if (data.isIntercepted()) return;
                if (!isEditSubtotal) return;

                data.setIntercepted(true);

                try {

                    if (mSteelyardDataModule == null)
                        mSteelyardDataModule = ExpandConfig.instance.getModuleManager().loadModule(SteelyardDataModule.class);

                    String steelyardMac = RunTimeData.steelyardInfo.getSteelyardMac();
                    List<OrderEntity.GoodEntity> goodEntities = mSteelyardDataModule.getGoodEntities(steelyardMac);
                    if(CollectionHelp.isEmpty(goodEntities))return;

                    int index = ((int) data.getNumber()) - 1;

                    OrderEntity.GoodEntity deleteGoodEntity = goodEntities.get(index);
                    if (goodEntities.size() < 10) {
                        if (!data.isFinally()) {
                            mSteelyardDataModule.removeGoodEntities(steelyardMac, index);
                        }
                    } else {
                        if (data.isFinally()) {
                            mSteelyardDataModule.removeGoodEntities(steelyardMac, index);
                        }
                    }


                    goodEntities = mSteelyardDataModule.getGoodEntities(steelyardMac);


                    OrderEntity.GoodEntity[] readGoodEntities = goodEntities==null? new OrderEntity.GoodEntity[0]: goodEntities.toArray(new OrderEntity.GoodEntity[goodEntities.size()]);
                    LinkBus.sendBroadcast(new OnSubtotalRealEvent(readGoodEntities,new OrderEntity.GoodEntity[]{deleteGoodEntity},false));


                    onSubtotalChanger(steelyardMac);
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }

    private volatile boolean isSubtotalGopay = false;
    public void goPayUI() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                isSubtotalGopay = false;
                if (mSteelyardDataModule == null)
                    mSteelyardDataModule = ExpandConfig.instance.getModuleManager().loadModule(SteelyardDataModule.class);



                OrderEntity orderEntity = souceList.size() == 0?null: mSteelyardDataModule.onlyCreateOrderEntity(RunTimeData.steelyardInfo.getSteelyardMac(),null);


                if(orderEntity!=null&&StringHelp.isEmpty(orderEntity.orderNum))
                    orderEntity = null;


                if (orderEntity == null || CollectionHelp.isEmpty(orderEntity.getGoods())) {


                    OrderEntity.GoodEntity goodEntity = mSteelyardDataModule.getCurWeightChangeGood(RunTimeData.steelyardInfo.getSteelyardMac());//mSteelyardDataModule.regLastWeightChangeToOrderGood(RunTimeData.steelyardInfo.getSteelyardMac());




                    if(goodEntity!=null && (goodEntity.unitPrice == 0||goodEntity.weight == 0)){
                        goodEntity = null;
                    }

                    if (goodEntity != null) {
                        isSubtotalGopay = true;

                        OrderEntity.GoodEntity goodEntity_ =  mSteelyardDataModule.regLastWeightChangeToOrderGood(RunTimeData.steelyardInfo.getSteelyardMac());
                        goodEntity = goodEntity_;
                        LinkBus.sendBroadcast(new OnSubtotalEvent(RunTimeData.steelyardInfo.getSteelyardMac(), goodEntity));
                    }else{
                        AppUIHelp.tryShowTipsSHORT( "无商品，重量或是价格不可为0");
                    }

                }else {


                    RunTimeData.orderEntity = orderEntity;





                    if(RunTimeData.isQuickPay){
                        FunHelp.quickPay();
                    }else {
                        //P.p("Bill-> SaleFragment ->showPay");
//                        RouterUINavigation.getInstance().showPay((BaseFragmentActivity) getActivity(), RunTimeData.tmpPayType);
                    }
                }
            }
        });


    }



    private void onPayOk( OrderEntity orderEntity) {
        createPrintInfo( orderEntity);
        if(RunTimeData.isAutoPrint) {
            ViewUIHelp.showTipsLong(getActivity(), "打印");
            printOrder();
        }
        RouterUINavigation.getInstance().showVipOrderFix((BaseFragmentActivity) getActivity());
//        RouterUINavigation.getInstance().showPaySuccess((BaseFragmentActivity) getActivity(), print, qrCode);
    }





    List<OrderEntity.GoodEntity> souceList = new ArrayList<>();

    private class MAdapter extends BaseHoldAdapter {
        public MAdapter() {
            super(holdCycleHelp());
        }

        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
            onListDataChanged();
        }

        @Override
        public IHoldView createHoldView(int position, View convertView, ViewGroup parent) {
            return new MHoldView();
        }

        @Override
        public int getCount() {
            return CollectionHelp.getSize(souceList);
        }

        @Override
        public Object getItem(int position) {
            return souceList.get(position);
        }
    }

    private class MHoldView extends LinearLayout implements IHoldView<OrderEntity.GoodEntity>, View.OnClickListener {

        private TextView tv_name, tv_price_unit, tv_weight, tv_totalPrice, tv_no;

        public MHoldView() {
            super(getActivity());
            ViewHelp.inflate(getActivity(), R.layout.item_sales, this);
            tv_no = (TextView) this.findViewById(R.id.tv_no);
            tv_name = (TextView) this.findViewById(R.id.tv_name);
            tv_price_unit = (TextView) this.findViewById(R.id.tv_price_unit);
            tv_weight = (TextView) this.findViewById(R.id.tv_weight);
            tv_totalPrice = (TextView) this.findViewById(R.id.tv_totalPrice);

//            findViewById(R.id.btn_delete).setOnClickListener(this);
        }

        private int position;

        @TargetApi(Build.VERSION_CODES.M)
        @Override
        public Object binData(OrderEntity.GoodEntity obj, int position, boolean isonPause) {
            this.position = position;


            setBackgroundColor(position % 2 == 1 ? Color.YELLOW : Color.TRANSPARENT);
            tv_no.setText("" + (position + 1));
            tv_name.setText(obj.goodName);
            tv_price_unit.setText(SteelardHelp.formatMoney(obj.unitPrice));
            if (obj.unitType == 2) {

                tv_weight.setText(((int) obj.weight) + "件");
            }else {
                tv_weight.setText(NumberHelp.formatMoney(obj.weight, 3, "--"));
            }
            tv_totalPrice.setText(SteelardHelp.formatMoney(obj.calPrice()));

            setTag(obj);
            return null;
        }

        @Override
        public void onClick(View view) {

            if (mSteelyardDataModule == null)
                mSteelyardDataModule = ExpandConfig.instance.getModuleManager().loadModule(SteelyardDataModule.class);


            String steelyardMac = RunTimeData.steelyardInfo.getSteelyardMac();
            if (mSteelyardDataModule != null)
                mSteelyardDataModule.removeGoodEntities(steelyardMac, position);

            souceList.clear();
            try {
                souceList.addAll(mSteelyardDataModule.getGoodEntities(steelyardMac));
            } catch (Exception e) {
            }

            adapter.notifyDataSetChanged();



//            LinkBus.sendBroadcast(new OnDeviceReceiverCmdEvent(extCmdRequestBody.getAction(), extCmdRequestBody));
        }
    }


    private boolean isEditSubtotal;


    public void editSubtotal(boolean is) {
        isEditSubtotal = is;
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {

                findViewById(R.id.v_editsubtotal).setVisibility(isEditSubtotal ? View.VISIBLE : View.GONE);
                AppConst.getModuleManager().loadModule(FunModule.class).setLockKeySwitch(isEditSubtotal);
            }
        });

    }

    public void clearAll() {
        onClearAllClick(null);
    }

    public void onClearAllClick(View v) {
        if (mSteelyardDataModule == null)
            mSteelyardDataModule = ExpandConfig.instance.getModuleManager().loadModule(SteelyardDataModule.class);

        String steelyardMac = RunTimeData.steelyardInfo.getSteelyardMac();
        if (mSteelyardDataModule != null) {

            List<OrderEntity.GoodEntity> goodEntities = mSteelyardDataModule.getGoodEntities(steelyardMac);
            if(!CollectionHelp.isEmpty(goodEntities))
            while (mSteelyardDataModule.removeGoodEntities(steelyardMac, 0) != 0) {
            }

            if(!CollectionHelp.isEmpty(goodEntities)) {
                OrderEntity.GoodEntity[] deletegoodEntities =  goodEntities.toArray(new OrderEntity.GoodEntity[goodEntities.size()]);
                LinkBus.sendBroadcast(new OnSubtotalRealEvent(new OrderEntity.GoodEntity[0],deletegoodEntities,false));
            }
        }

        RunTimeData.steelyardInfo.removeState(SteelyardInfo.RunTimeState_subtotal);


        onSubtotalChanger(steelyardMac);


    }

    private void onSubtotalChanger(String steelyardMac) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                souceList.clear();
                try {
                    souceList.addAll(mSteelyardDataModule.getGoodEntities(steelyardMac));
                } catch (Exception e) {
                }
                adapter.notifyDataSetChanged();
            }
        });
    }


    private float cur_allTotalPrice = 0;

    private float cur_weightTotalPrice = 0;



    private void upTprice1() {
        ((TextView) findViewById(R.id.tv_tprice1)).setText(SteelardHelp.formatMoney(cur_allTotalPrice == 0 ? (cur_allTotalPrice + cur_weightTotalPrice) : cur_allTotalPrice));
    }
    private void onListDataChanged() {

        float allWeight = 0, allTotalPrice = 0;
        for (OrderEntity.GoodEntity s : souceList) {
            allWeight += s.weight;
            allTotalPrice += s.calPrice();
        }

        ((TextView) (findViewById(R.id.tv_discount))).setText(
                Html.fromHtml("优惠折扣：<font color='#ff0000'>" + 0.00 + "</font>"));
        ((TextView) (findViewById(R.id.tv_discountAmount))).setText(
                Html.fromHtml("优惠金额：<font color='#ff0000'>" + 0.00 + "</font>"));

        ((TextView) (findViewById(R.id.tv_totalAmount))).setText(
                Html.fromHtml("消费金额：<font color='#ff0000'>" + SteelardHelp.formatMoney(allTotalPrice) + "</font>"));
        ((TextView) (findViewById(R.id.tv_payableAmount))).setText(
                Html.fromHtml("应付金额：<font color='#ff0000'>" + SteelardHelp.formatMoney(allTotalPrice) + "</font>"));

        cur_allTotalPrice = allTotalPrice;
        upTprice1();
//        ((TextView) findViewById(R.id.tv_tprice1)).setText(SteelardHelp.formatMoney(allTotalPrice));

        SaleManifestEntity saleManifestEntity = new SaleManifestEntity();
        saleManifestEntity.setSouceList(new ArrayList<>(souceList));
        saleManifestEntity.setDiscount("0.00");
        saleManifestEntity.setDiscountAmount("0.00");
        saleManifestEntity.setTotalAmount(SteelardHelp.formatMoney(allTotalPrice));
        saleManifestEntity.setPayableAmount(SteelardHelp.formatMoney(allTotalPrice));
        LinkBus.sendBroadcast(new OnSaleManifestSyncEvent(saleManifestEntity));


//            findViewById(R.id.v_pay_bar).setVisibility(View.GONE);

//            findViewById(R.id.v_pay_bar).setVisibility(View.VISIBLE);

        listView.setSelection(souceList.size());
    }



    SteelyardDataModule mSteelyardDataModule;

    String qrCode;
    String print;

    public void createPrintInfo( OrderEntity orderEntity) {

//        String steelyardMac = RunTimeData.steelyardInfo.getSteelyardMac();
        if (this.mSteelyardDataModule == null)
            this.mSteelyardDataModule = ExpandConfig.instance.getModuleManager().loadModule(SteelyardDataModule.class);

        SteelyardInfo steelyardInfo = RunTimeData.steelyardInfo;//mSteelyardDataModule.getSteelyardInfo(steelyardMac);

        qrCode = com.lkm.market2_0.m_imple.steelyardserver.server.Config.createQrCode(steelyardInfo, orderEntity.orderNum);

        print = salePrint.cretePrintContent(orderEntity, SteelardHelp.formatMoney(orderEntity.totalPrice), orderEntity.getGoods(), orderEntity.createTime, steelyardInfo,qrCode);

    }

    public void printOrder() {
        Task<String, Void, Boolean> task = createPrintTask(print, qrCode);
        task.action();
        task.execTask();
    }



    private Task<String, Void, Boolean> createPrintTask(String data, String QRData) {
        Task<String, Void, Boolean> task = new TaskAdapter<String, Void, Boolean>(new DefaultTaskExecutor(true), getClass().getName() + ".sendDate", MyApplication.getInstance().getTaskManager2()) {

            @Override
            public void onPreExecute() {
                super.onPreExecute();







            }

            @Override
            public void doExecuting(String param) {
                super.doExecuting(param);
                mTaskExecutor.executorDoAsyncExecuting(new RunnablePR<String, Void>() {
                    @Override
                    public Void run(String param) {
                        JsonP jsonP = new JsonP(param);
                        String data = jsonP.get("data").getAsString("");
                        String qr = jsonP.get("qr").getAsString("");

                        String orderInfoStr = data;


                        {
                            try {

                                PrinterHelp.print(orderInfoStr, qr);
                            } catch (Exception e) {
                            }
                        }


                        complete(true);
                        return null;
                    }
                }, param);
            }

        };
        HashMap<String, String> map = new HashMap<>();
        map.put("data", data);
        map.put("qr", QRData);

        task.setParam(new Gson().toJson(map));

        return task;
    }


    private SalePrint salePrint = new SalePrint();



}
